package com.swipemaster.music;

import android.content.Intent;
import android.media.MediaPlayer;

import com.swipemaster.R;
import com.swipemaster.common.Global;
import com.swipemaster.common.Prefs;

public class MusicPlayer
{
	public boolean continueMusic = false;
	/** Android API responsible for playing music. */
	private MediaPlayer mediaPlayer;
	/** Whether music is turned on or off. */
	private boolean enabled = Global.app.prefs.getBoolean(Prefs.MUSIC_KEY, true);
	/** Currently played song resource id. */
	private int playingSongResId;

	private final int songs[] =
	{ R.raw.electrodeus, R.raw.cant_get_more_then_this, R.raw.enigmate, R.raw.reggae, R.raw.lost_islands, R.raw.nova2,
			R.raw.track_like_this, R.raw.funky, R.raw.little_guitar, R.raw.jakub_koter3, R.raw.moonlight,
			R.raw.drippy2, R.raw.dark_dream, R.raw.lithop5, R.raw.eastern_vision, R.raw.freedom_cry, R.raw.escape,
			R.raw.koto, R.raw.ambienta2 };

	private final int menuSong = R.raw.deserve_to_be_loved;

	private final int customGameSong = R.raw.ambienta2;

	public boolean isEnabled()
	{
		return enabled;
	}

	public void playCustomGameSong()
	{
		playSong(customGameSong);
	}

	public void playLevelSong(int levelIndex)
	{
		playingSongResId = songs[levelIndex % songs.length];
		playSong(playingSongResId);
	}

	public void playMainTheme()
	{
		playSong(menuSong);
	}

	public void playSong(int songId)
	{
		playingSongResId = songId;
		Global.app.startService(new Intent(Global.app, MusicService.class));
	}

	public void setEnabled(boolean on)
	{
		enabled = on;
		Global.app.prefs.putObject(Prefs.MUSIC_KEY, enabled);

		if (enabled)
		{
			playSong(playingSongResId);
		}
		else
		{
			stop();
		}
	}

	public void stopMusic()
	{
		Global.app.stopService(new Intent(Global.app, MusicService.class));
	}

	void play()
	{
		if (!enabled)
		{
			return;
		}
		stop();
		if (mediaPlayer != null)
		{
			mediaPlayer.release();
		}
		// FIXME: Use 1 MediaPlayer instead of creating new one
		if (playingSongResId == 0)
		{
			return;
		}
		mediaPlayer = MediaPlayer.create(Global.app, playingSongResId);
		if (mediaPlayer != null)
		{
			mediaPlayer.setLooping(true);
			mediaPlayer.start();
		}
	}

	void stop()
	{
		if (mediaPlayer == null)
		{
			return;
		}
		if (mediaPlayer.isPlaying())
		{
			mediaPlayer.stop();
		}
	}
}
